<template>
    <div>
      <!--      面包屑导航区-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>

<!--      卡片视图区-->
      <el-card>
<!--        警告区域-->
        <el-alert
          title="注意：只允许为第三级分类设置相关参数"
          type="warning"
          :closable = 'false'
          show-icon
          center>
        </el-alert>
<!--        选择商品分类区域-->
        <el-row>
          <el-col>
            <span>选择商品分类：</span>
            <el-cascader
              v-model="selectedCateKeys"
              :options="cateList"
              :props="cateProps"
              @change="handleChange"
              clearable></el-cascader>
          </el-col>
        </el-row>

<!--        标签页切换区域-->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" :disabled="getTabStatus" @click="showAddDialog">添加参数</el-button>
            <el-table :data="manyParamsData" border stripe>
<!--              展开列-->
              <el-table-column type="expand">
                <template slot-scope="scope">
<!--                  循环渲染Tag标签-->
                  <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleTagClosed(i, scope.row)">{{item}}</el-tag>
<!--                  输入的文本框-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
<!--                  添加Tag的按钮-->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
<!--              索引列-->
              <el-table-column
                type="index"
                label="#">
              </el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParam(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" :disabled="getTabStatus" @click="showAddDialog">添加属性</el-button>
            <el-table
              :data="onlyParamsData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!--                  循环渲染Tag标签-->
                  <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleTagClosed(i, scope.row)">{{item}}</el-tag>
                  <!--                  输入的文本框-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!--                  添加Tag的按钮-->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column
                type="index"
                label="#">
              </el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParam(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>

<!--      添加分类的参数的对话框-->
      <el-dialog
        :title= "'添加' + getText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed">
        <!--    内容主体区域-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="动态参数" prop="attr_name" v-if="activeName === 'many'">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
          <el-form-item label="静态属性" prop="attr_name" v-else>
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!--    底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParam">确 定</el-button>
        </span>
      </el-dialog>

      <!--      修改分类的参数的对话框-->
      <el-dialog
        :title= "'修改' + getText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed">
        <!--    内容主体区域-->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="动态参数" prop="attr_name" v-if="activeName === 'many'">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
          <el-form-item label="静态属性" prop="attr_name" v-else>
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!--    底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParam">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
  export default {
    name: 'Params',
    data() {
      return {
        //被选择的商品分类的id
        selectedCateKeys: [],
        //商品分类列表
        cateList: [],
        //级联选择器的属性配置对象
        cateProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          checkStrictly: false
        },
        //当前选中的TabPane的name，即默认显示的标签页是动态参数页
        activeName: 'many',
        //动态参数的数据
        manyParamsData: [],
        //静态属性的数据
        onlyParamsData: [],

        //控制添加参数对话框显示与隐藏的标志
        addDialogVisible: false,
        addForm: {
          attr_name: ''
        },
        addFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' }
          ]
        },

        //控制修改参数对话框显示与隐藏的标志
        editDialogVisible: false,
        editForm: {
        },
        editFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' }
          ]
        },


      }
    },
    created() {
      this.getCateList();
    },
    methods: {
      async getCateList() {
        const {data: res} = await this.$http.get('categories', {params: {type: 3}});
        if (res.meta.status !== 200) return this.$message.error('获取分类列表失败!');
        // console.log(res);
        this.cateList = res.data;
        // console.log(this.cateList)
      },

      //级联选择器的选中项变化时，触发此函数
      handleChange() {
        // console.log(this.selectedCateKeys);
        //通过selectedCateKeys数组长度，判断是否选中三级分类
        this.getParamsData();
        this.manyParamsData = [];
        this.onlyParamsData = [];
      },

      //处理切换Tab选项卡
      handleTabClick() {
        // console.log(this.activeName)
        this.getParamsData();
      },

      //根据 this.activeName 获取动态参数、静态属性
      async getParamsData() {
        if (this.selectedCateKeys.length !== 3) {
          this.selectedCateKeys = [];
          return;
        }
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}});
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败!');

        console.log(res.data)
        //将获取到的attr_vals字符串转换成数组，便于数据渲染
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
          //控制输入文本框的显示与隐藏
          item.inputVisible = false
          //文本的内容
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyParamsData = res.data;
        }else {
          this.onlyParamsData = res.data;
        }
      },

      //打开添加参数对话框
      showAddDialog() {
        this.addDialogVisible = true;
      },

      //添加参数、属性
      addParam() {
        // console.log(this.addForm.attr_name);
        this.$refs.addFormRef.validate(async vaild => {
          if (!vaild) return;
          const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          });
          // console.log(res);
          if (res.meta.status !== 201) return this.$message.error('添加失败');
          this.$message.success('添加成功')
          this.addDialogVisible = false;
          this.getParamsData();
          })
      },

      //添加参数对话框关闭时，重置editFrom
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },

      async showEditDialog(id) {
        // console.log(id);
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {params: {attr_sel: this.activeName}});
        if (res.meta.status !== 200) return this.$message.error('查询参数失败!');
        console.log(res);
        this.editForm = res.data;
        this.editDialogVisible = true;
      },

      editParam() {
        this.$refs.editFormRef.validate(async vaild => {
          if (!vaild) return;
          const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          });
          console.log(res);
          if (res.meta.status !== 200) return this.$message.error('更新失败');
          this.$message.success('更新成功')
          this.editDialogVisible = false;
          this.getParamsData();
        })
      },

      //当关闭编辑参数对话框时，重置对话框的表单数据引用
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },

      // 根据参数的 attr_id 删除属性
      async removeParam(id) {
        const confirmRes = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        //如果确认删除，则confirmRes的返回值为 confirm
        //如果取消删除，则confirmRes的返回值为 cancel
        if (confirmRes === 'cancel') return this.$message.info('已取消删除');
        const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`);
        if (res.meta.status !== 200) return this.$message.error('删除失败');
        this.getParamsData();
        this.$message.success('删除成功');
      },

      //文本框失去焦点、被摁下回车，就会被触发，使文本框隐藏和提交文本内容
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = '';
          row.inputVisible = false;
          return;
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = '';
        row.inputVisible = false;

        // console.log(row);
        // 发起请求保存操作
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        });
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error('修改参数项失败');
        this.$message.success('修改参数项成功')
      },

      //点击按钮，显示文本输入框
      showInput(row) {
        row.inputVisible = true;
        //让文本框自动获得焦点
        //$nextTick 作用，就是当页面元素被重新渲染后，才会执行指定回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      async handleTagClosed(i, row) {
        console.log(i)
        row.attr_vals.splice(i, 1);
        console.log(row.attr_vals)
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        });
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error('修改参数项失败');
        this.$message.success('修改参数项成功')
      }
    },
    //计算属性
    computed: {
      //只有在选择了商品的分类后，添加参数和添加属性的按钮才能被点击
      getTabStatus() {
        if (this.selectedCateKeys.length !== 3) {
          return true;
        }else return false;
      },

      cateId() {
        if (this.selectedCateKeys.length === 3) {
          return this.selectedCateKeys[2];
        }
        return null;
      },

      getText() {
        if (this.activeName === 'many') {
          return '动态参数';
        }else return '静态属性';
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-row {
    margin-top: 15px;
  }
  el-cascader {
    width: 100%;
  }
  .el-tag {
    margin: 0 5px;
  }
  .input-new-tag {
    width: 150px;
  }
</style>
